#include"InetAddr.hpp"
#include"Logger.hpp"
#include"Comm.hpp"

#include<iostream>
#include<string>
#include<sys/types.h>
#include<sys/socket.h>
#include<arpa/inet.h>
#include<netinet/in.h>


void Usage(std::string proc)
{
    std::cout << "Usage: " << proc << " serverip serverport" <<std::endl;
}

//用户：创建套接字、无需显式绑定、发送连接请求、写、读
//./client serverip serverport
int main(int argc , char*argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 0;
    }
    std::string serverip = argv[1];
    uint16_t serverport = std::stoi(argv[2]);
    //创建网络地址
    int sockfd = socket(AF_INET , SOCK_STREAM , 0);
    if(sockfd < 0)
    {
        std::cerr << "创建套接字失败" <<std::endl;
        exit(SOCKET_CREATE_ERR);
    }
    std::cout << "创建套接字成功" <<std::endl;

    //不需要我们显式bind
    //向服务器发起请求，此处只让客户端发起一次请求，失败了不再重复发起请求
    //connect , 在发起请求的时候，OS会对sockfd 与随机的ip port 进行bind ,然后再向服务器发起请求
    //成功返回0失败返回-1
    InetAddr server(serverport, serverip);
    if(connect(sockfd , server.Addr() , server.Length())!= 0)
    {
        std::cerr  << "connect server error" << std::endl;
        exit(SOCKET_CONNECT_ERR);
    }
    std::cout << "connect server success" << std::endl;

    //客户端发送数据、读取数据
    while(true)
    {
        std::cout << "Please enter# ";
        std::string line;
        std::getline(std::cin , line);

        ssize_t n = write(sockfd , line.c_str() , line.size());
        if(n >= 0)
        {
            char buffer[1024];
            buffer[0]=0;
            ssize_t m = read(sockfd , buffer , sizeof(buffer)-1);
            if(m > 0)
            {
                buffer[m]=0;
                std::cout << buffer << std::endl;
            }
        }

    }
    return 0;
}